package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.model.product.BaseCategory1;
import com.atguigu.gmall.product.mapper.BaseCategory1Mapper;
import com.atguigu.gmall.product.service.BaseCategory1Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 一级分类的实现类
 */
@Service
public class BaseCategory1ServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1>
        implements BaseCategory1Service {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    /**
     * 条件查询
     *
     * @param baseCategory1
     * @return
     */
    @Override
    public List<BaseCategory1> search(BaseCategory1 baseCategory1) {
        //判断查询参数是否为空
        if (baseCategory1 ==null){
            //若没有查询所有
            return baseCategory1Mapper.selectList(null);
        }
        LambdaQueryWrapper wrapper = getCondition(baseCategory1);
        //执行查询
        List<BaseCategory1> baseCategory1s = baseCategory1Mapper.selectList(wrapper);
        //返回结果
        return baseCategory1s;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<BaseCategory1> pageSearch(Integer page, Integer size) {
        //执行查询
        IPage<BaseCategory1> result = baseCategory1Mapper.selectPage(new Page<>(page,size),null);
        //返回结果
        return result.getRecords();
    }

    /**
     * 条件分页查询
     *
     * @param baseCategory1
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<BaseCategory1> search(BaseCategory1 baseCategory1, Integer page, Integer size) {
        //构建查询条件
        LambdaQueryWrapper wrapper = getCondition(baseCategory1);
        //分页查询
        IPage<BaseCategory1> result = baseCategory1Mapper.selectPage(new Page<>(page,size),wrapper);
        //获取结果
        return result.getRecords();
    }

    /**
     * 条件构造
     * @param baseCategory1
     * @return
     */
    private LambdaQueryWrapper getCondition(BaseCategory1 baseCategory1){
        //定义条件构造器
        LambdaQueryWrapper<BaseCategory1> wrapper = new LambdaQueryWrapper<>();
        //若id不为空
        if (baseCategory1.getId() !=null){
            wrapper.eq(BaseCategory1::getId,baseCategory1.getId());
        }
        //若name不为空
        if (StringUtils.isNotEmpty(baseCategory1.getName())){
            wrapper.like(BaseCategory1::getName,baseCategory1.getName());
        }

        return wrapper;
    }
}
